<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 添加按钮 -->
    <el-button type="primary">添加角色</el-button>
    <!-- 表单 -->
    <el-table
      ref="multipleTable"
      :data="rolesList"
      tooltip-effect="dark"
      style="width: 100%"
      border
      stripe
    >
      <!-- 展开列 -->
      <el-table-column label="" type="expand">
        <template slot-scope="scope">
          <!-- 渲染一级权限 i1是索引-->
          <el-row
            :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']"
            v-for="(item1, i1) in scope.row.children"
            :key="item1.id"
          >
            <el-col :span="5">
              <el-tag closable @close="removeRolesById(scope.row, item1.id)">
                <!-- 插值表达式 -->
                {{ item1.authName }}
              </el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>

            <!-- 渲染二级 三级权限 这里的col中的span给的太大，会掉下去 -->
            <el-col :span="19">
              <!-- 通过for循环渲染二级权限 -->
              <el-row
                :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                v-for="(item2, i2) in item1.children"
                :key="item2.id"
              >
                <el-col :span="6">
                  <el-tag
                    type="success"
                    closable
                    @close="removeRolesById(scope.row, item2.id)"
                  >
                    {{ item2.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="18">
                  <el-tag
                    closable
                    @close="removeRolesById(scope.row, item3.id)"
                    type="danger"
                    v-for="(item3, i3) in item2.children"
                    :key="item3.id"
                  >
                    {{ item3.authName }}
                  </el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- 索引列 -->
      <el-table-column type="index" width="55" label="#"> </el-table-column>
      <el-table-column label="角色名称" width="250" prop="roleDesc">
      </el-table-column>
      <el-table-column label="角色描述" width="250" prop="roleName">
      </el-table-column>
      <!-- 这里指定了一个宽度，才能撑下三个按钮 -->
      <el-table-column label="操作" show-overflow-tooltip>
        <!-- 这里也是使用了 插槽 -->
        <template slot-scope="scope">
          <!-- 编辑按钮 -->
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.id)"
          ></el-button>
          <!-- 删除按钮 -->
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="deleteById(scope.row.id)"
          ></el-button>
          <el-tooltip
            class="item"
            effect="dark"
            content="分配设置"
            placement="top"
            :enterable="false"
          >
            <!-- 分配权限 -->
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRightDialog(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限的对话框 -->
    <el-dialog
      title="编辑用户权限"
      :visible.sync="rightDialogVisible"
      width="50%"
      @close="closeRightDialog"
    >
      <el-tree
        :data="rightList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKey"
        ref="rightsRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      rolesList: [],
      rightDialogVisible: false,
      //编辑用户权限
      rightList: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children',
      },
      //默认选中框的数组
      defKey: [],
      //即将分配权限的对象
      rolesId:[]
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    //提交选中的权限 ...是展开运算符 将数组展开 合并数组
    async allotRights(){
      const keys = [...this.$refs.rightsRef.getCheckedKeys(),
      ...this.$refs.rightsRef.getHalfCheckedNodes()
      ]
      // console.log(keys)
      //使用指定的符号将数组中的元素进行分割
      const idStr = keys.join(',')
      const {data:res} =await this.$http.post(`roles/${this.rolesId}/rights`,{rids:idStr})
      if(res.meta.status !==200) return this.$message.error("分配权限失败") 
      this.$message.success("分配权限成功")
      this.rightDialogVisible = false
      this.getRolesList()

    },
    //每次关闭对话框将 数组中的id进行清除，否则会产生积累
    closeRightDialog(){
      this.defKey = []

    },
    //通过递归的形式，获取三级权限的id，并将其保存到defKey数组中
    getLeafKeys(node, arr) {
      //如果当前节点不包含children属性，那么则是第三级属性
      if (!node.children) {
        return arr.push(node.id)
      }
      //遍历每个子节点，每次遍历获取其节点item，并根据这个节点将其放入数组中
     node.children.forEach(item => {
       this.getLeafKeys(item,arr)
       
     });
    },
    //显示编辑用户权限的对话框
    async setRightDialog(role) {
      this.rolesId = role.id
      this.rightDialogVisible = true
      const { data: res } = await this.$http.get('rights/tree')
      console.log(res)
      if (res.meta.status != 200) return this.$message.error('渲染列表失败')
      //递归获取三级节点的id
      this.getLeafKeys(role, this.defKey)
      this.rightList = res.data
    },
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      console.log(res)
      if (res.meta.status !== 200) return this.$message.error('渲染失败')
      this.rolesList = res.data
     
    },
    showEditDialog() {},
    deleteById() {},
    removeRolesById(role, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${rightId}`
          )
          if (res.meta.status !== 200)
            return this.$message.error('删除用户权限失败')
          console.log(res)
          //这样会导致页面的重新刷新
          // this.getRolesList()
          role.children = res.data
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
  },
}
</script>

<style scoped>
.bdbottom {
  border-bottom: 1px solid #eee;
}
.bdtop {
  border-top: 1px solid #eee;
}
.el-tag {
  margin: 7px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>